package com.example.myproject.controller;

import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.AvatarService;
import com.example.myproject.vo.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/avatar")
public class AvatarController {

    @Autowired
    private AvatarService avatarService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<String> uploadAvatar(@RequestPart("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ApiResponse.error(400, "请选择要上传的文件");
        }

        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();

            String avatarUrl = avatarService.uploadAvatar(userId, file);
            return ApiResponse.success(200, "上传成功", avatarUrl);
        } catch (Exception e) {
            return ApiResponse.error(500, "上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/url")
    public ApiResponse<String> getAvatarUrl() {
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();

            String avatarUrl = avatarService.getAvatarUrl(userId);
            return ApiResponse.success(200, "获取成功", avatarUrl);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取失败: " + e.getMessage());
        }
    }
}